from PyQt5 import QtCore
from PyQt5.QtCore import Qt, QObject
from PyQt5.QtGui import QBrush, QColor
from PyQt5.QtWidgets import QHBoxLayout, QTableWidgetItem, QHeaderView, QAbstractItemView, \
    QPushButton, QMenu, QAction, QMainWindow

from src.autoupdate.thread_check_update import ThreadCheckUpdate
from src.autoupdate.update_handler import UpdateHandler
from src.myapp.main_panel import MainPanel


class BootstrapWindow(QObject):

    def __init__(self):
        super().__init__()
        self.ui = QMainWindow()
        self.mainPanel = MainPanel()
        self.mainPanel.setupUi(self.ui)
        self.uh = UpdateHandler()

        # 菜单
        menu_start = self.mainPanel.menubar.addMenu('开始')
        menu_check_update = self.mainPanel.menubar.addMenu('关于')
        menu_check_update.addAction('检查更新')
        menu_check_update.triggered[QAction].connect(self.pop_check_update_window)

        # 初始化表格，定义对表格的操作
        self.init_person_table()
        # 快速定位表格某行
        row_num = self.quick_locate()
        self.quick_locate_scroll_to_row(row_num)
        # 点击单元格触发打印其内容
        self.mainPanel.tableWidget.itemClicked.connect(self.handle_item_click)

        # ”关闭“按钮
        cb = self.mainPanel.CloseBtn
        cb.clicked.connect(self.ui.close)  # 信号 connect 槽

    def pop_check_update_window(self):
        """
        检查最新版本，在异步task中进行
        """
        t = ThreadCheckUpdate()
        t.update_ui_signal.connect(self.refresh_when_found)
        t.timeout_signal.connect(self.refresh_when_timeout)
        t.start()
        self.uh.reset_default()
        self.show_check_update_window()

    def show_check_update_window(self):
        self.uh.display_window()

    def refresh_when_found(self, newest_version, content_str):
        self.uh.refresh_ui_when_found_new_version(newest_version, content_str)

    def refresh_when_timeout(self):
        self.uh.ui.label_2.setText("连接服务器超时！")
        self.uh.ui.label_2.setStyleSheet("color:red")

    def init_person_table(self):
        wafer_table = self.mainPanel.tableWidget
        # 4行
        wafer_table.setRowCount(20)
        # 3列
        wafer_table.setColumnCount(4)
        # 水平头标签，注意：必须先初始化行数和列数
        wafer_table.setHorizontalHeaderLabels(['A', 'B', 'C', 'Op'])
        wafer_table.verticalHeader().setVisible(False)
        # 设置表头自动占满表的全部宽度
        wafer_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # 只读
        wafer_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        # 点击一个位置后选中一整行
        wafer_table.setSelectionBehavior(QAbstractItemView.SelectRows)

        # 第一行第一个单元格
        new_item = QTableWidgetItem("Joseph")
        wafer_table.setItem(0, 0, new_item)

        # 第一行第二个单元格
        new_item = QTableWidgetItem('man')
        wafer_table.setItem(0, 1, new_item)

        # 第一行第三个单元格
        new_item = QTableWidgetItem('140')
        wafer_table.setItem(0, 2, new_item)

        # 第一行第四个单元格，按钮
        search_btn = QPushButton('Modify')
        search_btn.setDown(True)  # 按钮置为已按下的状态（深色）
        wafer_table.setCellWidget(0, 3, search_btn)

        # 循环创建单元格 19行 4列
        for i in range(1, 20):  # 1到19 不包含20
            for j in range(0, 4):  # 0到3 不包含4
                wafer_table.setItem(i, j, QTableWidgetItem(str(i) + "-" + str(j)))

        # 按第3列内容的字典序排序
        # wafer_table.sortItems(2, QtCore.Qt.SortOrder.AscendingOrder)

        # 自定义上下文菜单
        wafer_table.setContextMenuPolicy(Qt.CustomContextMenu)
        wafer_table.customContextMenuRequested.connect(self.generate_wafer_table_menu)

        # 布局
        con_layout = QHBoxLayout()
        con_layout.addWidget(wafer_table)
        self.ui.setLayout(con_layout)

    def quick_locate(self):
        """
        快速定位到包含指定文本的第一个单元格所在的行
        :return: row_num 行号
        """
        _row_num = -1

        text = '5-2'
        items = self.mainPanel.tableWidget.findItems(text,
                                                     QtCore.Qt.MatchFlag.MatchExactly | QtCore.Qt.MatchFlag.MatchContains)

        # list 判空和校验长度
        if items is not None and len(items) > 0:
            item = items[0]
            # 单元格的行号
            _row_num = item.row()
            # 选中单元格
            item.setSelected(True)
            # 设置单元格内容颜色
            item.setForeground(QBrush(QColor(255, 0, 0)))
            print(f'找到包含指定字符串的第一个单元格的行索引（从0开始）：{_row_num}')
        else:
            print('未找到包含指定字符串的单元格')
        return _row_num

    def quick_locate_scroll_to_row(self, _row_num):
        """
        快速定位到指定索引号的行
        :param _row_num:
        :return:
        """
        if _row_num >= 0:
            self.mainPanel.tableWidget.verticalScrollBar().setSliderPosition(_row_num)
            print(f'滚动条滑动到第{_row_num + 1}行')

    @staticmethod
    def handle_item_click(item):
        print('选中的单元格文本 =>' + item.text())

    def generate_wafer_table_menu(self, pos):
        """
        表格组件右键菜单
        :param pos:
        :return:
        """
        _row_num = -1
        # TODO for循环重复赋值给 _row_num 取表格最后一行的索引
        for i in self.mainPanel.tableWidget.selectionModel().selection().indexes():
            _row_num = i.row()

        print('*******当前行索引*******')
        print(_row_num)

        if _row_num >= 0:
            menu = QMenu()
            opt1 = menu.addAction(u'选项a')
            opt2 = menu.addAction(u'选项b')
            opt3 = menu.addAction(u'选项c')
            action = menu.exec(self.mainPanel.tableWidget.mapToGlobal(pos))  # todo what is mapToGlobal？
            if action == opt1:
                print('你选中了选项a，当前行文字内容是：',
                      self.mainPanel.tableWidget.item(_row_num, 0).text(),
                      self.mainPanel.tableWidget.item(_row_num, 1).text(),
                      self.mainPanel.tableWidget.item(_row_num, 2).text(),
                      self.mainPanel.tableWidget.item(_row_num, 3).text(),
                      )
            elif action == opt2:
                print('你选中了选项b，当前行文字内容是：',
                      self.mainPanel.tableWidget.item(_row_num, 0).text(),
                      self.mainPanel.tableWidget.item(_row_num, 1).text(),
                      self.mainPanel.tableWidget.item(_row_num, 2).text(),
                      self.mainPanel.tableWidget.item(_row_num, 3).text(),
                      )
            elif action == opt3:
                print('你选中了选项c，当前行文字内容是：',
                      self.mainPanel.tableWidget.item(_row_num, 0).text(),
                      self.mainPanel.tableWidget.item(_row_num, 1).text(),
                      self.mainPanel.tableWidget.item(_row_num, 2).text(),
                      self.mainPanel.tableWidget.item(_row_num, 3).text(),
                      )
            else:
                return
